<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col>
      <!--图元数据-->
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="80px" v-show="showSearch" >
        <el-form-item label="图元名称" prop="elementTitle">
          <el-input v-model="queryParams.elementTitle" placeholder="请输入图元名称" size="small" clearable style="width: 150px"/>
        </el-form-item>

        <el-form-item label="所属分类" prop="classId">
          <el-select @change="handleQuery" v-model="queryParams.classId" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in elementClassOptions" :key="item.classId" :label="item.className" :value="item.classId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="图元状态" prop="statusCode">
          <el-select @change="handleQuery" v-model="queryParams.statusCode" size="small" clearable style="width: 150px" placeholder="请选择">
            <el-option key="" label="全部" value=""/>
            <el-option v-for="item in statusOptions" :key="item.dictCode" :label="item.dictName" :value="item.dictCode"/>
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker @change="handleQuery" v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"/>
        </el-form-item>

        <el-form-item>
          <el-button type="primary"  size="mini" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery('queryForm')">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary"  v-hasPermi="['saveTopoElementInfo']"  icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" v-hasPermi="['updateTopoElementInfo']"  icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate">修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" v-hasPermi="['deleteTopoElementInfo']"  icon="el-icon-delete" size="mini" :disabled="single" @click="handleDelete">删除</el-button>
        </el-col>

        <right-toolbar :showSearch.sync="showSearch" @queryTable="queryTopoElementInfoPageResList" :columns="columns"></right-toolbar>
      </el-row>

        <el-table ref="multipleTable" :stripe="true" v-loading="loading" :data="dataList" @selection-change="handleSelectionChange"
                  @sort-change='tableSortChange' :default-sort="{prop: 'sort', order: 'descending'}">
          <el-table-column type="selection" align="center"/>
          <el-table-column label="图元名称" align="left" prop="elementTitle"/>
          <el-table-column label="图元图标" align="center" prop="elementImg" width="150">
            <template slot-scope="scope">
              <img width="80" height="80" :src="scope.row.elementImg" :onerror="$store.state.defaultAvatar"/>
            </template>
          </el-table-column>
          <el-table-column label="图元状态" align="left" prop="statusName" width="150">
            <template slot-scope="scope">
              <span :style="'color:'+scope.row.statusColor">{{scope.row.statusName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="所属分类" align="left" prop="className" width="200"/>
          <el-table-column label="创建部门" align="left" prop="createDeptName"   width="250"/>
          <el-table-column label="创建时间" align="left" prop="createTime" sortable='custom' width="200" />
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" v-hasPermi="['updateTopoElementInfo']" icon="el-icon-edit"  @click="handleUpdate(scope.row)">修改</el-button>
              <el-button size="mini" type="text" v-hasPermi="['deleteTopoElementInfo']" icon="el-icon-delete"  @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
                    @pagination="queryTopoElementInfoPageResList"/>
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="addUpdateOpen" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="addUpdateOpenRules"  label-width="80px">

        <el-form-item label="所属分类" prop="classId">
          <el-select :hide-required-asterisk="true" v-model="form.classId" clearable style="width: 100%;" placeholder="请选择">
            <el-option v-for="item in elementClassOptions" :key="item.classId" :label="item.className" :value="item.classId"/>
          </el-select>
        </el-form-item>

        <el-form-item label="图元名称" prop="elementTitle">
          <el-input :hide-required-asterisk="true" autocomplete="off" v-model="form.elementTitle" placeholder="请输入图元名称" maxlength="30" />
        </el-form-item>

        <el-form-item label="图元图标" prop="elementImg" ref="elementImg">
          <el-upload
            ref="image"
            class="avatar-uploader"
            action="#"
            accept="image/jpeg,image/gif,image/png,image/jpg"
            :show-file-list="false"
            :http-request="requestUpload"><!--覆盖默认上传-->
            <img v-if="form.elementImg" :src="form.elementImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>

        </el-form-item>

      <!--  <el-form-item label="图标宽度" prop="imgWidth">
          <el-input-number :hide-required-asterisk="true" v-model="form.imgWidth" :min="80" :max="10000" label="图标宽度" />
        </el-form-item>

        <el-form-item label="图标高度" prop="imgHeight">
          <el-input-number :hide-required-asterisk="true" v-model="form.imgHeight" :min="80" :max="10000" label="图标高度" />
        </el-form-item>-->

        <el-form-item label="图元状态" prop="statusCode">
          <el-select :hide-required-asterisk="true" v-model="form.statusCode" clearable placeholder="请选择"  style="width: 100%;">
            <el-option
              v-for="item in statusOptions"
              :key="item.dictCode"
              :label="item.dictName"
              :value="item.dictCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input-number :hide-required-asterisk="true" v-model="form.sort" :min="1" :max="10000" label="排序" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancelAddUpdateOpen">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {queryTopoElementInfoPageResList, saveTopoElementInfo, updateTopoElementInfo, deleteTopoElementInfoByElementId} from '@/api/topo/elementInfo'
  import {queryNormalSelectTopoElementClassResList} from '@/api/topo/elementClass'
  import { getDicListByDictCodeList } from '@/api/common/dict'
  import { imageSingleUpload } from '@/api/common/fileUpload'
  //默认查询参数
  let defaultQueryParams = {
    elementTitle: undefined,
    classId: undefined,
    startTime: undefined,
    endTime: undefined,
    statusCode: "",
    page: 1,
    rows: 10
  }
  export default {
    name: "elementInfoAdmin",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 显示搜索条件
        showSearch: true,
        // table表格数据
        dataList: [],
        // 日期范围
        dateRange: [],
        // 弹出层标题
        title: "",
        // 是否显示新增修改弹出层
        addUpdateOpen: false,
        // 图元状态
        statusOptions: [],
        //图元分类
        elementClassOptions: [],
        // 增加修改表单参数
        form: {},
        // 查询参数
        queryParams: { ...defaultQueryParams },
        //列信息
        columns: [],
        // 新增修改表单校验
        addUpdateOpenRules: {
          elementTitle: [
            { required: true, message: "图元名称必须填写",trigger: "blur" },
          ],
          classId: [
            { required: true, message: "所属分类必须选择"},
          ],
          statusCode: [
            { required: true, message: "图元状态必须选择",trigger: "blur" }
          ],
          elementImg: [
            { required: true, message: "图元图标必须上传"},
          ],
          imgHeight: [
            { required: true, message: "图标高度必须填写"},
          ],
          imgWidth: [
            { required: true, message: "图标宽度必须填写"},
          ],
          sort: [
            { required: true, message: "排序不能为空",trigger: "blur" },
          ]
        }
      }
    },
    created() {
      this.initDict();
      this.queryNormalSelectTopoElementClassResList();
      this.queryTopoElementInfoPageResList();
    },
    methods: {
      //获取数据字典
      initDict(){
        let dictArr = ["STATUS"];
        getDicListByDictCodeList(dictArr).then(res => {
          this.statusOptions = JSON.parse(JSON.stringify(res.data['STATUS']));
        });
      },
      //上传图元图标
      requestUpload(file) {
        const dataForm = new FormData()
        dataForm.append('file', file.file)
        imageSingleUpload(dataForm).then(result => {
          if(result.errorCode===0){
            this.form.elementImg = result.data.fileAbsolutePath;
            this.$refs["elementImg"].clearValidate()
          }else{
            this.$message.error(result.message)
          }
        })
      },

      //获取图元分类
      queryNormalSelectTopoElementClassResList(){
        queryNormalSelectTopoElementClassResList({}).then(res => {
          this.elementClassOptions = res.data;
        });
      },

      /** 查询图元列表 */
      queryTopoElementInfoPageResList() {
        this.loading = true
        queryTopoElementInfoPageResList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.loading = false
        })
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.elementId)
        this.single = selection.length !== 1;
        this.multiple = !selection.length
      },
      //排序
      tableSortChange(column){
        //格式化排序参数，构建中
        this.orderByFormat(this.queryParams,column);
        //执行查询方法
        this.queryTopoElementInfoPageResList()
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.addUpdateOpen = true;
        this.queryNormalSelectTopoElementClassResList();
        this.title = "添加图元";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        //修改表单填充
        this.form = {...row};
        this.addUpdateOpen = true;
        this.queryNormalSelectTopoElementClassResList();
        this.title = "修改图元";
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        row = row.isTrusted ? this.$refs.multipleTable.selection[0] : row;
        this.$confirm('是否确认删除所选图元?', "警告", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          type: "warning"
        }).then(function() {
          const elementId={elementId:row.elementId}
          return deleteTopoElementInfoByElementId(elementId);
        }).then(response => {
          this.$modal.msgSuccess(response.message)
          this.queryTopoElementInfoPageResList();
        }).catch(function() {});
      },

      /** 提交保存或修改按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.elementId !== undefined) {
              updateTopoElementInfo(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTopoElementInfoPageResList();
                this.addUpdateOpen = false
              });
            } else {
              saveTopoElementInfo(this.form).then(response => {
                this.$modal.msgSuccess(response.message)
                this.queryTopoElementInfoPageResList();
                this.addUpdateOpen = false
              });
            }
          }
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1
        this.queryTopoElementInfoPageResList()
      },
      /** 重置按钮操作 */
      resetQuery(fromId) {
        this.dateRange = [];
        this.resetForm(fromId);
        this.handleQuery()
      },
      // 取消修改增加弹出层按钮
      cancelAddUpdateOpen() {
        this.addUpdateOpen = false
      },
      // 表单重置
      reset() {
        this.form = {
          elementId: undefined,
          elementTitle: undefined,
          sort: 1,
          bindDevice:0,
          editLink:0,
          classId: undefined,
          statusCode: "",
          elementImg:undefined,
          imgHeight:150,
          imgWidth:150
        };
        this.resetForm('form')
      }
    }
  }
</script>

<style lang="less" scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    line-height: 100px;
    display: block;
  }
</style>
